package com.sairui.Xiaoruilib;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.Window;

import com.sairui.Xiaoruilib.bean.SearchBean;
import com.sairui.Xiaoruilib.manager.PopupWindowHelper;
import com.sairui.Xiaoruilib.util.GsonConvert;
import com.sairui.Xiaoruilib.util.NetworkUtil;
import com.sairui.Xiaoruilib.util.SoftHideKeyBoardUtil;
import com.sairui.Xiaoruilib.util.sp.PreferenceImpl;
import com.sairui.Xiaoruilib.widgets.NewVoiceView;
import com.sairui.Xiaoruilib.widgets.WXTouchView;
import com.sairui.xiroruilib.recognize.VoiceRecognizeManager;
import com.sairui.xiroruilib.speak.SpeakManager;
import com.sairui.xiroruilib.speak.Speaker;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Random;

public class XiaoRuiActivity extends Activity implements View.OnClickListener {
    private WebView mWebView;
    private EditText mKeyBord;
    private RelativeLayout mBottomKeyBord;
    private WXTouchView mVoiceInput;
    private RelativeLayout mBottomVoice;
    private View mMengCeng;
    private RelativeLayout mNoData;
    private ProgressBar mProgressBar;

    private SearchBean mSearchBean;//与h5交互实体类

    private MediaPlayer mMediaStartPlayer;//开始语音识别播放声音
    private MediaPlayer mMediaEndPlayer;//结束语音识别播放声音

    private XiaoRuiHeaderManager mTitle;//标题

    //是否加载H5发生错误
    private boolean isNetError = false;
    //用于处理第一次加载完成，因为不知原因，网页progress 为 100 会执行2次
    private boolean isFirstLoadWeb = true;

    private PopupWindowHelper popupWindowHelper;
    private View voicePopView;
    private TextView mVoiceContent;
    private TextView mVoiceContentHint;
    private NewVoiceView mVoiceView;
    private TextView mVoiceHintContent;
    private ImageView mPopRobotIcon;
    private AnimationDrawable animationDrawable;
    private LinearLayout mLLNoVoiceData;
    private LinearLayout mLLSpeakTimeLess;

    private long mSpeakTime = 0;//说话的时间
    private String mBaiDuSpeakContent = "";
    private Boolean isPointCancel = true;//是否手指取消

    public static Intent getInstance(Context context) {
        return new Intent(context, XiaoRuiActivity.class);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(MResource.getIdByName(this,"layout","activity_xiao_rui"));

        //初始化语音识别和语音合成
        SpeakManager.getInstance().init("11226642",
                "jtwTBFTuZezBRr5cgPnUNCWf", "6Aey6KaHlxrObCPTmkYNgxVDDFAqx0km", this);
        VoiceRecognizeManager.getInstance().init("11226642",
                "jtwTBFTuZezBRr5cgPnUNCWf", "6Aey6KaHlxrObCPTmkYNgxVDDFAqx0km", this);

        initWidgets();

        switch (PreferenceImpl.getPreference(this).getInteger(XiaoRuiLibSp.IDENTIFY_SPEAK)) {
            case 1:
                SpeakManager.getInstance().setCustomVoice(Speaker.COMMON_MAN);
                break;
            case 2:
                SpeakManager.getInstance().setCustomVoice(Speaker.COMMON_WOMAN);
                break;
            case 3:
                SpeakManager.getInstance().setCustomVoice(Speaker.EMOTION_MAN);
                break;
            case 4:
                SpeakManager.getInstance().setCustomVoice(Speaker.EMOTION_CHILD);
                break;

        }

        VoiceRecognizeManager.getInstance().setRecognizeListener(new VoiceRecognizeManager.VoiceRecognizeListener() {
            @Override
            public void onStart() {
                mMediaStartPlayer.start();
            }

            @Override
            public void onEnd() {
                if (TextUtils.isEmpty(mBaiDuSpeakContent)) {
                    VoiceRecognizeManager.getInstance().cancelRecognize();
                    //如果不是手指上滑动引起的取消
                    if (!isPointCancel) {
                        mLLSpeakTimeLess.setVisibility(View.INVISIBLE);
                        mLLNoVoiceData.setVisibility(View.VISIBLE);
                        mVoiceView.emptyVoice();
                    }
                }
            }

            @Override
            public void onPartialResult(String result) {
                mVoiceContentHint.setVisibility(View.INVISIBLE);
                mBaiDuSpeakContent = result;
                setDataToWidget(mVoiceContent, result);
            }

            @Override
            public void onFinalResult(String result) {
                setDataToWidget(mVoiceContent, result);
                popupWindowHelper.dismiss();
                VoiceRecognizeManager.getInstance().cancelRecognize();
                mVoiceView.emptyVoice();
                mMengCeng.setVisibility(View.GONE);
                mSearchBean.setQueryContent(result);
                String msg = GsonConvert.toJson(mSearchBean);
                mWebView.loadUrl("javascript:createConversation('" + msg + "')");
            }

            @Override
            public void onVolume(int volumePercent, int volume) {
                if (volumePercent != 0) {
                    volumePercent = volumePercent / 2;
                    mVoiceView.setVoiceLevel(volumePercent);//音量大小
                    Random random = new Random();
                    mVoiceView.setVoiceLevel(random.nextInt(20));//音量大小
                    mVoiceView.setVoiceLevel(random.nextInt(20));//音量大小
                }
            }

        });


        //标题栏
        mTitle = new XiaoRuiHeaderManager(new WeakReference<Activity>(this));
        //设置是否可以语音播放图表
        mTitle.setVoiceIcon(PreferenceImpl.getPreference(XiaoRuiActivity.this).getBoolean(XiaoRuiLibSp.IS_CAN_SPEAK, true));

        mTitle.setTitleClickListener(new XiaoRuiHeaderManager.TitleClickListener() {
            @Override
            public void headerClick(XiaoRuiHeaderManager.HeaderClickType type, View view) {
                //去除底部语音输入弹框
                popupWindowHelper.dismiss();
                mMengCeng.setVisibility(View.GONE);
                mVoiceView.emptyVoice();
                switch (type) {
                    case HELP_TYPE://标题-快捷帮助
                        if (!NetworkUtil.isConnected(XiaoRuiActivity.this)) {
                            showShortToast("网络不给力，请检查网络设置");
                            return;
                        }
                        mSearchBean.setQueryContent("帮助");
                        String msg = GsonConvert.toJson(mSearchBean);
                        mWebView.loadUrl("javascript:createConversation('" + msg + "')");
                        break;
                    case MENU_TYPE://标题-左侧菜单
                        finish();
                        break;
                    case VOICE_TYPE://标题-声音
                        Boolean isCanSpeak = PreferenceImpl.getPreference(XiaoRuiActivity.this).getBoolean(XiaoRuiLibSp.IS_CAN_SPEAK, true);
                        PreferenceImpl.getPreference(XiaoRuiActivity.this).put(XiaoRuiLibSp.IS_CAN_SPEAK, !isCanSpeak);
                        mTitle.setVoiceIcon(!isCanSpeak);
                        if (isCanSpeak) {
                            SpeakManager.getInstance().stop();
                        }
                        SpeakManager.getInstance().setVoiceSwitch(!isCanSpeak);
                        break;
                }
            }
        });

        //当有弹出框是重新刷新界面
        SoftHideKeyBoardUtil.assistActivity(this, new SoftHideKeyBoardUtil.RelayoutListener() {
            @Override
            public void relayout() {
            }

            @Override
            public void upSoft(int heightDifference) {
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
                if (resourceId > 0) {
                    heightDifference -= getResources().getDimensionPixelSize(resourceId);
                }
                mWebView.loadUrl("javascript:boxScroll()");
                TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, -(heightDifference * 1.0f));
                animation.setFillAfter(true);
                animation.setDuration(100);
                mWebView.setAnimation(animation);

            }

            @Override
            public void closeSoft(int heightDifference) {
                TranslateAnimation animation = new TranslateAnimation(0.0f, 0.0f, 0.0f, 0.0f);
                animation.setFillAfter(true);
                animation.setDuration(100);
                mWebView.setAnimation(animation);
            }
        });

        //初始化 开始语音识别播放声音 和 结束语音识别播放声音
        mMediaStartPlayer = MediaPlayer.create(this, MResource.getIdByName(this,"raw","start"));
        mMediaEndPlayer = MediaPlayer.create(this, MResource.getIdByName(this,"raw","end"));

        mSearchBean = new SearchBean();
        initWebView();
        mWebView.loadUrl("https://106.15.205.249:50000/fine-robot/xiaorui/index");

        mVoiceInput.setTouchListener(new WXTouchView.TouchListener() {
            @Override
            public void start_recognize() {
                if (!NetworkUtil.isConnected(XiaoRuiActivity.this)) {
                    showShortToast("网络不给力，请检查网络设置");
                    return;
                }

                mLLSpeakTimeLess.setVisibility(View.INVISIBLE);
                mLLNoVoiceData.setVisibility(View.INVISIBLE);
                SpeakManager.getInstance().stop();

                startTextListener();

                isPointCancel = false;
                mSpeakTime = System.currentTimeMillis();
                mBaiDuSpeakContent = "";
                startRecognize();

                mVoiceContent.setTextColor(ContextCompat.getColor(XiaoRuiActivity.this, MResource.getIdByName(XiaoRuiActivity.this,"color","main_voice_pop_black")));
                mVoiceHintContent.setTextColor(ContextCompat.getColor(XiaoRuiActivity.this, MResource.getIdByName(XiaoRuiActivity.this,"color","main_voice_pop_grey")));
                setDataToWidget(mVoiceContent, "");
                setDataToWidget(mVoiceHintContent, "手指上滑 取消发送");
                mVoiceView.setCancel(false);
                mMengCeng.setVisibility(View.VISIBLE);
                popupWindowHelper.showAsPopUp(XiaoRuiActivity.this,mBottomVoice);
            }

            @Override
            public void cancel_recognize() {
                if (!NetworkUtil.isConnected(XiaoRuiActivity.this)) {
                    return;
                }

                isPointCancel = true;
                VoiceRecognizeManager.getInstance().stopRecognize();
                VoiceRecognizeManager.getInstance().cancelRecognize();
                mVoiceContent.setTextColor(ContextCompat.getColor(XiaoRuiActivity.this, MResource.getIdByName(XiaoRuiActivity.this,"color","main_voice_pop_grey")));
                mVoiceHintContent.setTextColor(ContextCompat.getColor(XiaoRuiActivity.this, MResource.getIdByName(XiaoRuiActivity.this,"color","main_voice_pop_black")));
                setDataToWidget(mVoiceHintContent, "手指松开 取消发送");
                mVoiceView.setCancel(true);
                mBaiDuSpeakContent = "";
            }

            @Override
            public void end_recognize() {
            }

            @Override
            public void actionUp() {
                if (!NetworkUtil.isConnected(XiaoRuiActivity.this)) {
                    return;
                }
                VoiceRecognizeManager.getInstance().stopRecognize();
                isInTextListener = false;
                mVoiceContentHint.setVisibility(View.INVISIBLE);
                if ((System.currentTimeMillis() - mSpeakTime) < 700) {
                    VoiceRecognizeManager.getInstance().cancelRecognize();
                    mLLSpeakTimeLess.setVisibility(View.VISIBLE);
                    mLLNoVoiceData.setVisibility(View.INVISIBLE);
                }
                mSpeakTime = 0;
                mMediaEndPlayer.start();
                //如果是手指上滑引起的取消
                if (isPointCancel) {
                    popupWindowHelper.dismiss();
                    mMengCeng.setVisibility(View.GONE);
                    mVoiceView.emptyVoice();
                }
            }
        });
        //底部语音弹窗
        voicePopView = LayoutInflater.from(this).inflate(MResource.getIdByName(XiaoRuiActivity.this,"layout","pop_new_main_voice"), null);
        mVoiceContent = voicePopView.findViewById(MResource.getIdByName(XiaoRuiActivity.this,"id","voice_content"));
        mVoiceContentHint = voicePopView.findViewById(MResource.getIdByName(this,"id","voice_content_hint"));
        mVoiceView = voicePopView.findViewById(MResource.getIdByName(this,"id","voice_view"));
        mVoiceHintContent = voicePopView.findViewById(MResource.getIdByName(this,"id","voice_hint"));
        mPopRobotIcon = voicePopView.findViewById(MResource.getIdByName(this,"id","robot_icon"));
        mLLNoVoiceData = voicePopView.findViewById(MResource.getIdByName(this,"id","no_voice_data"));
        mLLSpeakTimeLess = voicePopView.findViewById(MResource.getIdByName(this,"id","speak_time_less"));
        animationDrawable = (AnimationDrawable) mPopRobotIcon.getBackground();
        if (animationDrawable != null && !animationDrawable.isRunning()) {
            animationDrawable.start();
        }
        popupWindowHelper = new PopupWindowHelper(voicePopView);

        mKeyBord.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    if (!NetworkUtil.isConnected(XiaoRuiActivity.this)) {
                        showShortToast("网络不给力，请检查网络设置");
                        return false;
                    }
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘
                    if ("".equals(getText(mKeyBord))) {
                        return false;
                    }
                    mMengCeng.setVisibility(View.GONE);
                    mSearchBean.setQueryContent(getText(mKeyBord));
                    String msg = GsonConvert.toJson(mSearchBean);
                    setDataToWidget(mKeyBord, "");
                    mWebView.setVisibility(View.VISIBLE);
                    mWebView.loadUrl("javascript:createConversation('" + msg + "')");
                }
                return false;
            }
        });
    }


    private void initWidgets() {
        mWebView = findViewById(MResource.getIdByName(this,"id","web_view"));
        mKeyBord = findViewById(MResource.getIdByName(this,"id","key_bord"));
        mBottomKeyBord = findViewById(MResource.getIdByName(this,"id","bottom_key_bord"));
        mVoiceInput = findViewById(MResource.getIdByName(this,"id","voice_input"));
        mBottomVoice = findViewById(MResource.getIdByName(this,"id","bottom_voice"));
        mMengCeng = findViewById(MResource.getIdByName(this,"id","men_ceng"));
        mNoData = findViewById(MResource.getIdByName(this,"id","rl_no_data"));
        mProgressBar = findViewById(MResource.getIdByName(this,"id","pb_progressbar"));
        findViewById(MResource.getIdByName(this,"id","input_type_key_bord")).setOnClickListener(this);
        findViewById(MResource.getIdByName(this,"id","input_type_voice")).setOnClickListener(this);
        findViewById(MResource.getIdByName(this,"id","rl_no_data")).setOnClickListener(this);
        findViewById(MResource.getIdByName(this,"id","men_ceng")).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == MResource.getIdByName(this,"id","input_type_key_bord")) {
            mBottomKeyBord.setVisibility(View.INVISIBLE);
            mBottomVoice.setVisibility(View.VISIBLE);
            dismissSoftInput(mKeyBord);

        } else if (i == MResource.getIdByName(this,"id","input_type_voice")) {//去除底部语音输入弹框
            popupWindowHelper.dismiss();
            mMengCeng.setVisibility(View.GONE);
            mVoiceView.emptyVoice();
            mBottomKeyBord.setVisibility(View.VISIBLE);
            mBottomVoice.setVisibility(View.GONE);
            mKeyBord.setFocusable(true);
            mKeyBord.setFocusableInTouchMode(true);
            mKeyBord.requestFocus();
            mKeyBord.findFocus();
            showSoftInput(mKeyBord);

        } else if (i == MResource.getIdByName(this,"id","rl_no_data")) {
            //去除底部语音输入弹框
            popupWindowHelper.dismiss();
            mMengCeng.setVisibility(View.GONE);
            mVoiceView.emptyVoice();

            isFirstLoadWeb = true;
            isNetError = false;
            mWebView.reload();

        } else if (i == MResource.getIdByName(this,"id","men_ceng")) {//去除底部语音输入弹框
            popupWindowHelper.dismiss();
            mMengCeng.setVisibility(View.GONE);
            mVoiceView.emptyVoice();

        }
    }

    public void dismissSoftInput(EditText input) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(), 0); //强制隐藏键盘
    }

    public void showSoftInput(EditText input) {
        InputMethodManager immm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        immm.showSoftInput(input, InputMethodManager.SHOW_FORCED);// 显示输入法
    }

    private void initWebView() {
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setDefaultTextEncodingName("UTF-8");
        webSetting.setBuiltInZoomControls(false);// 显示缩放按钮(wap网页不支持)
        webSetting.setUseWideViewPort(false);// 支持双击缩放(wap网页不支持)
        //能够执行JavaScript脚本
        webSetting.setJavaScriptEnabled(true);
        MainJsForAndorid mMainJsForAndorid = new MainJsForAndorid(new WeakReference<Activity>(this));
        mWebView.addJavascriptInterface(mMainJsForAndorid, "android");
        mMainJsForAndorid.setJsListener(new MainJsForAndorid.JsListener() {
            @Override
            public void hideKeyboard() {
                dismissSoftInput(mKeyBord);
            }

            @Override
            public void webSpeak(String speak) {
                speak(speak);
            }
        });
        //支持在当前WebView窗口加载网页
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                Log.e("onReceivedError", s + "  " + s1 + "   " + i);
                if ((i == -1 || i == -8) && "net::net::<unknown>".equals(s)) {
                    isNetError = true;
                    ViewGroup.LayoutParams params = mNoData.getLayoutParams();
                    params.height = mWebView.getHeight();
                    mNoData.setLayoutParams(params);
                    mNoData.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                //进度发生变化,可以获取到进度
                if (null != mProgressBar) {
                    mProgressBar.setProgress(newProgress);
                    if (newProgress == 100 && isFirstLoadWeb) {
                        isFirstLoadWeb = false;
                        if (!isNetError) {
                            mNoData.setVisibility(View.GONE);
                        }
                        mProgressBar.setVisibility(View.GONE);
                        String msg = GsonConvert.toJson(mSearchBean);
                        mWebView.loadUrl("javascript:queryConversationHistory('" + msg + "')");
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

        });
    }

    protected void showShortToast(String pMsg) {
        if (pMsg == null || "".equals(pMsg) || "null".equals(pMsg)) {
            return;
        }
        if (isFinishing()) {
            return;
        }
        if (pMsg.startsWith("Unable to resolve host")) {
            return;
        }
        if (pMsg.startsWith("Failed to connect")) {
            pMsg = "网络不给力，请检查网络设置";
        }

        Toast.makeText(this, pMsg, Toast.LENGTH_SHORT).show();
    }

    private Boolean isInTextListener = true;
    private int mTextListenerPosition = 1;

    public void startTextListener() {
        isInTextListener = true;
        mTextListenerPosition = 1;
        mVoiceContentHint.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isInTextListener) {
                    try {
                        Thread.sleep(400);
                        XiaoRuiActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String text = "我正在听";
                                for (int i = 0; i <= mTextListenerPosition % 3; i++) {
                                    text = String.valueOf(text + ".");
                                }
                                mTextListenerPosition++;
                                mVoiceContentHint.setText(text);
                            }
                        });
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void startRecognize() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 923);
        } else {
            VoiceRecognizeManager.getInstance().startRecognize();
        }

    }

    protected void setDataToWidget(TextView view, String s) {
        if (s != null) {
            view.setText(s);
        }
    }

    protected void setDataToWidget(EditText view, String s) {
        if (s != null) {
            view.setText(s);
            view.setSelection(s.length());
        }
    }

    protected String getText(EditText edittext) {
        if (edittext == null) {
            return "";
        }
        return edittext.getText().toString().trim();
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void speak(String content) {
        String permissions[] = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.
            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        } else {
            SpeakManager.getInstance().speak(content);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SpeakManager.getInstance().stop();
        mWebView.destroy();
        VoiceRecognizeManager.getInstance().setRecognizeListener(null);
    }
}
